package com.benny_driving_dri.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.http.HttpStatus;

import android.util.Log;

public class NetToolPost {
	private static int TIME_OUT = 12000;
	private static String ENCODING = "utf-8";

	public static String sendPostRequest(String urlPath, String data) {
		Log.i("net_test", "url: " + urlPath + "\n data" + data);
		byte[] entityData = data.getBytes();
		String resDataFinal = "";
		try {
			URL url = new URL(urlPath);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setConnectTimeout(TIME_OUT);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-Type", "text/html");
			con.setRequestProperty("Charset", ENCODING);
			con.setRequestProperty("Content-Length",
					String.valueOf(entityData.length));
			OutputStream out = con.getOutputStream();
			Log.i("net_test", entityData.toString());
			out.write(entityData);
			out.flush();
			out.close();
			int resCode;
			if ((resCode = con.getResponseCode()) == HttpStatus.SC_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						con.getInputStream(), ENCODING));
				String resData = null;
				while ((resData = br.readLine()) != null) {
					resDataFinal += resData;
				}
				br.close();
			} else {
				resDataFinal = resCode + "";
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
		return resDataFinal;
	}
}
